package prometheus

import (
	"fmt"
	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"longmen/server/config/global"
	appServer "longmen/server/pkg/common/app/server"
	"net/http"
)

type GrpcMetrics struct {
	reg         *prometheus.Registry
	GrpcMetrics *grpc_prometheus.ServerMetrics
}

func NewGrpcMetrics() *GrpcMetrics {
	// Register standard server metrics and customized metrics to registry.
	metrics := grpc_prometheus.NewServerMetrics()
	metrics.EnableHandlingTimeHistogram()
	instance := &GrpcMetrics{
		reg:         prometheus.NewRegistry(),
		GrpcMetrics: metrics,
	}

	instance.reg.MustRegister(instance.GrpcMetrics)
	return instance
}

func (g *GrpcMetrics) StarHttpServer(s *appServer.Server, runPort int) {
	g.GrpcMetrics.InitializeMetrics(s.Server)
	grpc_prometheus.Register(s.Server)
	g.reg.MustRegister(
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
		collectors.NewGoCollector(),
	)
	httpServer := &http.Server{
		Handler: promhttp.InstrumentMetricHandler(
			g.reg, promhttp.HandlerFor(g.reg, promhttp.HandlerOpts{}),
		),
		Addr: fmt.Sprintf("0.0.0.0:%d", runPort),
	}

	go func() {
		global.Log.Info("[prometheus]: start port is:  ", runPort)
		if err := httpServer.ListenAndServe(); err != nil {
			global.Log.Fatal("[prometheus]: Unable to start a http server.")
		}
	}()
}
